from __future__ import absolute_import, division, print_function

import atexit
import time
import random
import numpy as np
import pyeit.eit.protocol as protocol
import pyeit.mesh as mesh
from pyeit.eit.fem import EITForward
from pyeit.mesh.wrapper import PyEITAnomaly_Circle
import zmq
import time

""" 0. build mesh """
n_el = 16  # nb of electrodes

mesh_obj = mesh.create(n_el, h0=0.1)

""" 1. problem setup """
#anomaly = PyEITAnomaly_Circle(center=[0.5, 0.5], r=0.1, perm=10.0)
#mesh_new = mesh.set_perm(mesh_obj, anomaly=anomaly, background=1.0)

""" 2. FEM forward simulations """
# setup EIT scan conditions
# adjacent stimulation (dist_exc=1), adjacent measures (step_meas=1)
protocol_obj = protocol.create(n_el, dist_exc=1, step_meas=1, parser_meas="std")

# calculate simulated data
fwd = EITForward(mesh_obj, protocol_obj)
#v0 = fwd.solve_eit()
#v1 = fwd.solve_eit(perm=mesh_new.perm)

context = zmq.Context(2)
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:8100")
while True:
    anomaly = PyEITAnomaly_Circle(center=[random.uniform(-0.5,0.5), random.uniform(-0.5,0.5)], r=0.1, perm=10.0)
    mesh_new = mesh.set_perm(mesh_obj, anomaly=anomaly, background=1.0)
    v1 = fwd.solve_eit(perm=mesh_new.perm)
    socket.send(v1)
    print("sended")
    time.sleep(0.05)
    
atexit.register(socket.close(),print("closed socket"))
